﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Xml.Linq;

using BLL;

namespace CTRL
{
    public class CtrlCountry
    {
        private static CtrlCountry instance = null;
        private static readonly object padlock = new object();
        private static readonly string countryListURL = String.Format("{0}\\{1}", System.IO.Directory.GetCurrentDirectory(), "country.xml");
        private List<Country> countryList;

        public CtrlCountry()
        {
            countryList = new List<Country>();
            LoadCountryFile();
        }

        public Country FindCountry(string tld)
        {
            return countryList.FirstOrDefault(x => x.TLD.Equals(tld));
        }

        public List<Country> LoadCountryFile()
        {
            countryList.Clear();

            XDocument.Load(countryListURL).Descendants("country").ToList().ForEach(x => countryList.Add(new Country { Name = x.Element("name").Value.ToString(), TLD = x.Element("tld").Value.ToString() }));

            return countryList;
        }

        public static CtrlCountry Instance
        {
            get
            {
                lock (padlock)
                {
                    if (instance == null)
                    {
                        instance = new CtrlCountry();
                    }

                    return instance;
                }
            }
        }
    }
}